package me.qi.kancha.vo.base;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.hibernate.validator.constraints.Range;
import org.springframework.util.ObjectUtils;

import javax.validation.constraints.Min;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分页查询条件
 *
 * @author sun
 * @date 2019/2/26 10:17
 */
public abstract class PageParam implements Serializable {

    /**
     * 页码,值>0,默认1
     */
    @Min(value = 1)
    private Integer page = 1;

    /**
     * 每页数据条数,1-100,默认10
     */
    @Range(min = 1, max = 100)
    private Integer size = 10;

    /**
     * type:field;...... type 1 asc 0 desc
     */
    private String order;

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    /**
     * 默认按创建时间降序
     *
     * @return
     */
    public Page pageInstance() {
        List<OrderItem> orderList = new ArrayList<>();
        if (ObjectUtils.isEmpty(order)) {
            orderList.add(OrderItem.desc("created_time"));
        } else {
            for (String o : order.split(";")) {
                String[] split = o.split(":");
                if ("1".equals(split[0])) {
                    orderList.add(OrderItem.asc(split[1]));
                } else {
                    orderList.add(OrderItem.desc(split[1]));
                }
            }
        }
        return pageInstance(orderList);
    }

    /**
     * 自定义排序规则
     *
     * @param items
     * @return
     */
    public Page pageInstance(OrderItem... items) {
        return pageInstance(Arrays.asList(items));
    }

    /**
     * 自定义排序规则
     *
     * @return
     */
    public Page pageInstance(List<OrderItem> list) {
        Page page = new Page<>(this.page, this.size);
        page.setOrders(list);
        return page;
    }

    public Integer getSize() {
        return (size == null) ? 10 : size;
    }

    public Integer getPage() {
        return (page == null) ? 1 : page;
    }

    public void setPage(@Min(value = 1) Integer page) {
        this.page = page;
    }

    public void setSize(@Range(min = 0, max = 100) Integer size) {
        this.size = size;
    }
}
